package com.rrd.dw.mr.gzip.kafka;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ucredit.babel.common.model.BaseModel;
import com.ucredit.babel.common.model.RecordType;
import com.ucredit.babel.common.model.tianji.TianjiAntifraudData;
import com.ucredit.babel.common.model.tianji.TianjiAntifraudV2Record;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper.Context;

import java.io.IOException;

/**
 * 天机反欺诈接口v2
 *
 * @author renzhanzheng
 */

public class TianjiAntifraudV2Parse extends  ParseBase{
    private Text val = new Text();
    private Text key = new Text();

    /**
     *
     * 天机反欺诈接口v2
     * @param model
     * @throws IOException
     * @throws InterruptedException
     * @return
     */
    @Override
    public boolean parseJob(Context context, BaseModel<?> model, String successful) throws IOException, InterruptedException {

        TianjiAntifraudV2Record obj = (TianjiAntifraudV2Record)model;
        TianjiAntifraudData data = obj.getData();
        JSONObject info = JSON.parseObject(data.getData()) == null ? new JSONObject() : JSON.parseObject(data.getData());
        JSONObject tianji = info.getJSONObject("tianji_api_agentce_antifraudv2_response") == null ? new JSONObject() : info.getJSONObject("tianji_api_agentce_antifraudv2_response");

        JSONArray riskList = tianji.getJSONArray("riskInfo");
        String riskCode = riskList.size() >= 1 ? riskList.getJSONObject(0).getString("riskCode") : "";
        StringBuilder sb = getBaseInfo(obj, successful);

        //状态码
        sb.append(info.getString("error")).append(CRT001);
        //请求标识
        sb.append(info.getString("request_id")).append(CRT001);
        //表示该条记录能否查到1\能查到-1\查不到
        sb.append(tianji.getString("found")).append(CRT001);
        //表示该条记录中的身份证能否查到1\能查到-1\查不到
        sb.append(tianji.getString("idFound")).append(CRT001);
        //0-100\欺诈分值\值越高欺诈可能性越大
        sb.append(tianji.getString("riskScore")).append(CRT001);
        //风险码
        sb.append(riskCode).append(CRT001);

        key.set(getKey());
        val.set(sb.toString().replace("\n", " ").replace("\r", " "));
        context.write(key, val);
        return true;
    }

    @Override
    public String getTableName() {
        return "kafka_babel_tianji_fraudv2_inc";
    }

    @Override
    public String getType() {
        return RecordType.TIANJI_ANTIFRAUDV2_RECORD.toString();
    }

    @Override
    public String getComment() {
        return "天机反欺诈接口v2";
    }
}
